package com.taotao.wechat.business;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.WechatUser;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.util.MyRestTemplate;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class User {
    private String urlFormat_detail_base = "https://api.weixin.qq.com/cgi-bin/user/info";
    private String urlFormat_detail = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";

    public static void main(String[] args) {
        User user = new User();
        user.insertUser("bameng", "oxT3Ojuz1a8MpRJ_YGXkPIFimrmQ");
    }

    public void insertUser(String appKey, String openId) {
        WechatUser condition = new WechatUser();
        condition.setAppId(appKey);
        condition.setOpenId(openId);
        condition.setStatus(Constant.STATUS_ENABLE);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "wechatUser.listAll", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> data = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                Accesstoken accesstoken = new Accesstoken(appKey);
                String accessToken = accesstoken.getAccesstoken();
                WechatUser user = getUserDetailFormWWW(accessToken, openId);
                user.setAppId(appKey);
                user.setSubscribe_time(new Date().getTime());
                if (data == null || data.size() == 0) {
                    //新增
                    MyRopClient.getRopClient("").buildClientRequest()
                            .post(user, BaseResponse.class, "wechatUser.insert", "1.0");
                } else if (data != null && data.size() > 0) {
                    //更新
                    user.setId(Long.parseLong(data.get(0).get("id").toString()));
                    MyRopClient.getRopClient("").buildClientRequest()
                            .post(user, BaseResponse.class, "wechatUser.update", "1.0");
                }
            }
        }
    }

    public void updateUser(String appKey, String openId) {
        Accesstoken accesstoken = new Accesstoken(appKey);
        String accessToken = accesstoken.getAccesstoken();
        if (accessToken.length() > 0) {
            WechatUser user = getUserDetailFormWWW(accessToken, openId);
            user.setAppId(appKey);
            user.setStatus(Constant.STATUS_ENABLE);
            MyRopClient.getRopClient("").buildClientRequest()
                    .post(user, BaseResponse.class, "wechatUser.update", "1.0");
        }
    }

    public void deleteUser(String appKey, String openId){
        WechatUser condition = new WechatUser();
        condition.setAppId(appKey);
        condition.setOpenId(openId);
        condition.setStatus(Constant.STATUS_DELETE);
        MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "wechatUser.update", "1.0");
    }

    public WechatUser getUserDetailFormWWW(String accessToken, String openId){
        WechatUser wechatUser = new WechatUser();
        wechatUser.setOpenId(openId);
        RestTemplate restTemplate = new MyRestTemplate();
        LinkedHashMap<String, Object> result = restTemplate.getForObject(String.format(urlFormat_detail, accessToken, openId), LinkedHashMap.class);
        if (result.get("errcode") != null && result.get("errcode").toString().equalsIgnoreCase("48001")) {
            //api unauthorized,没有api访问权限，不再获取用户基本信息
            return wechatUser;
        }
        String subscribe = result.get("subscribe")  != null ? result.get("subscribe").toString() : "";
        String openid = result.get("openid") != null ? result.get("openid").toString() : "";
        String nickname = result.get("nickname") != null ? result.get("nickname").toString() : "";
        String sex = result.get("sex") != null ? result.get("sex").toString() : "";
        String language = result.get("language") != null ? result.get("language").toString() : "";
        String city = result.get("city") != null ? result.get("city").toString() : "";
        String province = result.get("province") != null ? result.get("province").toString() : "";
        String country = result.get("country") != null ? result.get("country").toString() : "";
        String headimgurl = result.get("headimgurl") != null ? result.get("headimgurl").toString() : "";
        String subscribe_time = result.get("subscribe_time") != null ?result.get("subscribe_time").toString() : "";
        String unionid = result.get("unionid") != null ? result.get("unionid").toString() : "";

        if (subscribe != null && subscribe.length() > 0) {
            wechatUser.setSubscribe(Integer.parseInt(subscribe));
        }
        wechatUser.setNickName(nickname);
        if (sex != null && sex.length() > 0) {
            wechatUser.setSex(Integer.parseInt(sex));
        }
        wechatUser.setLanguage(language);
        wechatUser.setCity(city);
        wechatUser.setProvince(province);
        wechatUser.setCountry(country);
        wechatUser.setHeadImgUrl(headimgurl);
        if (subscribe_time != null && subscribe_time.length() > 0) {
            wechatUser.setSubscribe_time(Long.parseLong(subscribe_time));
        }
        wechatUser.setUnionId(unionid);
        return wechatUser;
    }

    /**
     * 如果存在此用户，则升级成会员；如果不存在此用户，则添加用户并升级成会员
     */
    public static boolean setUserToMember(String appId, String openId, Integer memberStatus) {
        WechatUser condition = new WechatUser();
        condition.setAppId(appId);
        condition.setOpenId(openId);
        condition.setStatus(Constant.STATUS_ENABLE);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "wechatUser.listAll", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                WechatUser wechatUser = new WechatUser();
                wechatUser.setAppId(appId);
                wechatUser.setOpenId(openId);
                wechatUser.setStatus(Constant.STATUS_ENABLE);
                wechatUser.setMemberStatus(memberStatus);

                List<LinkedHashMap<String, Object>> dataList = (List<LinkedHashMap<String, Object>>)baseResponse.getData();
                if (dataList != null && dataList.size() > 0) {
                    Long id = Long.parseLong(dataList.get(0).get("id").toString());
                    wechatUser.setId(id);
                    MyRopClient.getRopClient("").buildClientRequest()
                            .post(wechatUser, BaseResponse.class, "wechatUser.update", "1.0");
                } else {
                    wechatUser.setIsOldUser(Constant.IS_OLD_USER);
                    wechatUser.setSubscribe_time(DateTimeUtil.getDateMillis(new Date()));
                    MyRopClient.getRopClient("").buildClientRequest()
                            .post(wechatUser, BaseResponse.class, "wechatUser.insert", "1.0");
                }
                return true;
            }
        }
        return false;
    }
}
